package com.godme.user.endpoint;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.godme.service.code.CodeManager;
import com.godme.service.user.UserManager;
import com.godme.user.sentinel.UserSentinelResource;
import com.godme.user.service.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;

@DubboService(interfaceClass = UserManager.class)
public class UserManagerImpl implements UserManager {

    @DubboReference
    private CodeManager codeManager;

    @Resource
    private UserService userService;

    @SentinelResource(value = "isRegistered", fallback = "isRegisteredFallback", blockHandler = "isRegisteredBlock", fallbackClass = UserSentinelResource.class, blockHandlerClass = UserSentinelResource.class)
    public boolean isRegistered(String mail){
        return userService.isRegistered(mail);
    }

    @SentinelResource(value = "auth", fallback = "authFallback", blockHandler = "authBlock", fallbackClass = UserSentinelResource.class, blockHandlerClass = UserSentinelResource.class)
    public boolean auth(String mail, String password){
        return userService.auth(mail, password);
    }

    @SentinelResource(value = "sign", fallback = "signFallback", blockHandler = "signBlock", fallbackClass = UserSentinelResource.class, blockHandlerClass = UserSentinelResource.class)
    public String sign(String mail, String password){
        return userService.sign(mail, password);
    }

    @SentinelResource(value = "register", fallback = "registerFallback", blockHandler = "registerBlock", fallbackClass = UserSentinelResource.class, blockHandlerClass = UserSentinelResource.class)
    public boolean register(String mail, String password, String code){
        if(isRegistered(mail)){
            return false;
        }
        boolean codeValid = 0 == codeManager.validCode(mail, code);
        if(codeValid){
            userService.register(mail, password);
        }
        return codeValid;
    }

    @SentinelResource(value = "check", fallback = "checkFallback", blockHandler = "checkBlock", fallbackClass = UserSentinelResource.class, blockHandlerClass = UserSentinelResource.class)
    public String check(String token){
        return userService.check(token);
    }
}
